/** 导出需要携带token，此处采用原生XMLHttpRequest去下载文件流 */
import Cookies from "js-cookie";

export function download(url: string , name: string){
    let baseURL = import.meta.env.VITE_API_URL;

    function createObjectURL(object:Blob) {
        return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
    }
    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    xhr.open('get', baseURL + url);  //url填写后台的接口地址，如果是post，在formData append参数（参考原文地址）
    xhr.setRequestHeader("SA-TOKEN", Cookies.get('token'));
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
        if (this.status == 200) {
            let blob = this.response;
            // let filename = params.fileName;
            // console.log(this.response)
            // if (window.navigator.msSaveOrOpenBlob) {
            //     navigator.msSaveBlob(blob,filename);
            // } else {
            //     let a = document.createElement('a');
            //     let url = createObjectURL(blob);
            //     a.href = url;
            //     a.download = filename;
            //     document.body.appendChild(a);
            //     a.click();
            //     window.URL.revokeObjectURL(url);
            // }
            let a = document.createElement('a');
            let url = createObjectURL(blob);
            a.href = url;
            a.download = name ;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
        }
    };
    xhr.send(formData);
}